package com.ruoyi.quartz.task;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.enumeration.SySelfServiceBookingOrderLogEnum;
import com.ruoyi.system.enumeration.SyTraditionalReservationEnum;
import com.ruoyi.system.service.*;
import com.ruoyi.system.util.AbdulEmptyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


@Component("orderTask")
public class OrderTask {
    @Autowired
    private SyTraditionalReservationService syTraditionalReservationService;

    @Autowired
    private SySelfServiceBookingOrderLogService logService;

    @Autowired
    private IMemberOverviewService memberOverviewService;

    @Autowired
    private IMemberListService memberListService;

    @Autowired
    private IMemberLevelService memberLevelService;

    private static final Logger logger = LoggerFactory.getLogger(OrderTask.class);

    /**
     * 预订订单超时取消
     */

    public void checkAndCancelOrders() {
        System.out.println("【定时任务-预订订单超时取消】开始执行：每分钟执行一次");
        Date now = new Date();
        Date updateTime = new Date(); // 统一更新时间

        LambdaQueryWrapper<SyTraditionalReservation> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(SyTraditionalReservation::getStatus, SyTraditionalReservationEnum.STATUS_WAIT_RESERVATION.getKey());
        wrapper.le(SyTraditionalReservation::getAutomaticallyCancelTime, now);

        List<SyTraditionalReservation> list = syTraditionalReservationService.list(wrapper);
        if (list == null || list.isEmpty()) {
            System.out.println("本次任务无待处理订单");
            return;
        }

        List<SyTraditionalReservation> outTimeList = new ArrayList<>();
        for (SyTraditionalReservation reservation : list) {
            if (reservation.getStatus().equals(SyTraditionalReservationEnum.STATUS_WAIT_RESERVATION.getKey())) {
                reservation.setStatus(SyTraditionalReservationEnum.STATUS_WAIT_CONFIRM.getKey());
                reservation.setUpdateTime(updateTime);
                //添加取消日志
                addLog(reservation.getBookingPhone(), reservation.getBookingDesk(), reservation.getBookingOrderNumber(), reservation.getTableClassification(), SySelfServiceBookingOrderLogEnum.CANCEL.getCode(), reservation.getBookingPerson(), reservation.getStoreId());
                outTimeList.add(reservation);
            }
        }

        try {
            // 可选：分批更新
            final int batchSize = 50;
            for (int i = 0; i < outTimeList.size(); i += batchSize) {
                int end = Math.min(i + batchSize, outTimeList.size());
                List<SyTraditionalReservation> subList = outTimeList.subList(i, end);
                syTraditionalReservationService.updateBatchById(subList);
            }
            System.out.println("成功更新" + outTimeList.size() + "条超时订单");
        } catch (Exception e) {
            System.err.println("批量更新超时订单失败" + e);
        }
    }


    private void addLog(String BookingPhone, String BookingDesk, String BookingOrderNumber, String TableClassification, Integer type, String BookingPerson, Long storeId) {
        SySelfServiceBookingOrderLog log = new SySelfServiceBookingOrderLog();
        log.setPhone(BookingPhone);
        log.setDesk(BookingDesk);
        log.setBookingNumber(BookingOrderNumber);
        log.setTableClassification(TableClassification);
        log.setType(type);
        log.setVipMessage(BookingPerson);
        log.setCreateBy("admin");
        log.setCreateTime(new Date());
        log.setStoreId(storeId);
        logService.save(log);
    }

    /**
     * 会员统计 一天生成一条 每十分钟更新一次
     */
    public void memberOverview(Integer time) {
        logger.info("【定时任务 - 会员统计】开始执行：每{}分钟执行一次", time);
        LocalDate today = LocalDate.now();
        LocalDateTime startOfDay = today.atStartOfDay(); // 当天 00:00:00
        LocalDateTime endOfDay = today.atTime(LocalTime.MAX); // 当天 23:59:59
        logger.debug("查询当天（{} 至 {}）的会员统计记录", startOfDay, endOfDay);
        // 查询当天的统计记录
        LambdaQueryWrapper<MemberOverview> overviewWrapper = Wrappers.lambdaQuery();
        overviewWrapper.between(MemberOverview::getCreateTime, Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant()),
                Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant()));
        MemberOverview existingOverview = memberOverviewService.getOne(overviewWrapper);

        MemberOverview memberOverview;
        if (existingOverview != null) {
            // 如果已存在当天记录，则使用该记录进行更新
            logger.info("检测到当天已存在会员统计记录，ID: {}", existingOverview.getId());
            memberOverview = existingOverview;
        } else {
            // 否则新建记录
            logger.info("当天无会员统计记录，准备新增");
            memberOverview = new MemberOverview();
            memberOverview.setCreateTime(new Date()); // 设置创建时间为当前时间
        }
        List<MemberList> list = memberListService.list();
        if (!AbdulEmptyUtils.isEmpty(list)) {
            memberOverview.setTotalMembers((long) list.size());

            // 正常/停用会员数
            long activeCount = list.stream().filter(item -> item.getMemberStatus() == 1).count();
            long inactiveCount = list.stream().filter(item -> item.getMemberStatus() == 2).count();
            memberOverview.setActiveMembers(activeCount);
            memberOverview.setInactiveMembers(inactiveCount);

            Set<Long> collect = list.stream().map(MemberList::getMemberLevelId).collect(Collectors.toSet());
            LambdaQueryWrapper<MemberLevel> levelWrapper = Wrappers.lambdaQuery();
            levelWrapper.select(MemberLevel::getLevelName, MemberLevel::getId).in(MemberLevel::getId, collect);
            List<MemberLevel> memberLevels = memberLevelService.list(levelWrapper);

            if (!AbdulEmptyUtils.isEmpty(memberLevels)) {
                // 获取不同的会员等级数量
                long goldCount = memberLevels.stream().filter(level -> "黄金会员".equals(level.getLevelName())).count();
                long regularCount = memberLevels.stream().filter(level -> "普通会员".equals(level.getLevelName())).count();
                memberOverview.setGoldMembersWithDiscount(goldCount);
                memberOverview.setRegularMembers(regularCount);
            }
            // 统计当日新增会员数量
            long newMembersToday = list.stream()
                    .filter(member -> {
                        LocalDateTime createTime = member.getCreateTime().toInstant()
                                .atZone(ZoneId.systemDefault())
                                .toLocalDateTime();
                        return !createTime.isBefore(startOfDay) && !createTime.isAfter(endOfDay);
                    })
                    .count();
            memberOverview.setNewMembers(newMembersToday);
            // 自助创建和后台创建人数
            long selfServiceCount = list.stream().filter(item -> "客人自助".equals(item.getCreateBy())).count();
            long backendCount = list.stream().filter(item -> !"客人自助".equals(item.getCreateBy())).count();
            memberOverview.setSelfServiceCreated(selfServiceCount);
            memberOverview.setBackendCreated(backendCount);
        }
        if (existingOverview != null) {
            logger.info("更新会员总览记录");
            memberOverview.setUpdateTime(new Date());
            memberOverviewService.updateById(memberOverview);
        } else {
            logger.info("新增会员总览记录");
            memberOverviewService.save(memberOverview);
        }
        logger.info("【定时任务 - 会员统计】执行结束");
    }

}
